﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace MododorWebAPI.Filter
{
    public class RateLimitFilter:IAsyncActionFilter
    {
        private readonly IMemoryCache memoryCache;
        public RateLimitFilter(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }

        public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string? remoteIP = context?.HttpContext?.Connection?.RemoteIpAddress?.ToString();
            string cacheKey = $"LastVisitIP_{remoteIP}";
            long? lastTick = memoryCache.Get<long?>(cacheKey);
            if (lastTick is null || Environment.TickCount64-lastTick>1000)
            {
                 memoryCache.Set<long?>(cacheKey, Environment.TickCount64,TimeSpan.FromSeconds(10));
                return next();
            }
            context.Result = new ContentResult() { StatusCode = 429, Content = "访问过快，请等待一秒" };
            return Task.CompletedTask;

        }
    }
}
